package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.ClientReceiverInfoDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.SupplierDealerSearchParam;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.company.ClientReceiverInfoMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.company.ClientReceiverInfoVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangyong
 */
@Service
public class ClientReceiverInfoService {

  @Autowired
  private ClientReceiverInfoMapper clientReceiverInfoMapper;

  @Autowired
  private FastGenClient fastGenClient;

  @Autowired
  private CompanyInfoMapper companyInfoMapper;

  @Autowired
  private CompanyDealerMapper companyDealerMapper;

  @Transactional(rollbackFor = Exception.class)
  public ErrorCode save(ClientReceiverInfoVO clientReceiverInfoVO) throws Exception {
    if (null == clientReceiverInfoVO || null == clientReceiverInfoVO.getOrgId()
        || null == clientReceiverInfoVO.getDealerOrgId()) {
      throw new Exception("未获取到公司或者客户公司信息");
    }

    ClientReceiverInfoDO clientReceiverInfoDO = new ClientReceiverInfoDO();
    BeanUtils.copyProperties(clientReceiverInfoVO, clientReceiverInfoDO);
    String id = clientReceiverInfoVO.getId();
    if (StringUtils.isBlank(id)){
      clientReceiverInfoDO.setId(fastGenClient.textGuid().getValue());
      clientReceiverInfoDO.setAddressCode(genAddressCode());
      return clientReceiverInfoMapper.insert(clientReceiverInfoDO)>0? ErrorCode.Success:ErrorCode.Failure;
    }
    return clientReceiverInfoMapper.update(clientReceiverInfoDO)>0? ErrorCode.Success:ErrorCode.Failure;
  }

  @Transactional(rollbackFor = Exception.class)
  public ErrorCode update(ClientReceiverInfoVO clientReceiverInfoVO) throws Exception {
    ClientReceiverInfoDO clientReceiverInfoDO = new ClientReceiverInfoDO();
    BeanUtils.copyProperties(clientReceiverInfoVO, clientReceiverInfoDO);
    return clientReceiverInfoMapper.update(clientReceiverInfoDO)>0? ErrorCode.Success:ErrorCode.Failure;
  }


  public ClientReceiverInfoVO getClientReceiverInfo(String id){
    ClientReceiverInfoVO clientReceiverInfoVO = new ClientReceiverInfoVO();
    ClientReceiverInfoDO clientReceiverInfoDO = clientReceiverInfoMapper.selectById(id);
    BeanUtils.copyProperties(clientReceiverInfoDO,clientReceiverInfoVO);
    return clientReceiverInfoVO;
  }

  /**
   * 生成地址编码，要求：不重复，容易对比（人工对比地址编码是否相同，来合并单据）
   * 生成方式：年月日-时分秒-循环自增的数字
   *
   * 可能产生重复数据的情况：
   * 1.批量导入地址，1秒内新增9999条以上地址，加上Thread.sleep(1)限制此种情况，对系统正常操作没啥影响
   * 2.超高并发：一秒内并发超过9999条数据，也不太可能，所以也安全
   *
   * @return
   */
  private String genAddressCode() {
    Integer seq = clientReceiverInfoMapper.getNextCodeSeq();
    try {
      Thread.sleep(1);
    } catch (InterruptedException e) {
      // nothing
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd-HHmmss");
    String result = sdf.format(new Date());
    result = result + "-" + String.format("%04d", seq);
    return result;
  }


  /**
   * 删除客户公司收货信息
   *
   * @param id
   * @return
   */
  public ErrorCode deleteById(String id) {
    return clientReceiverInfoMapper.deleteById(id)>0? ErrorCode.Success:ErrorCode.Failure;
  }

  /**
   * 获取客户公司收货信息
   *
   * @return
   */
  public PageCommonVO list(SearchCommonVO<ClientReceiverInfoVO> condition) {
      PageCommonVO pageCommonVO = new PageCommonVO();
      PageHelperPlus.orderBy("RECEIVER_NAME");
      PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
      List<ClientReceiverInfoVO> receiverInfoVOS = new ArrayList<>();
      List<ClientReceiverInfoDO> receiverInfoDOS = clientReceiverInfoMapper.list(condition.getFilters());
      if (!CollectionUtils.isEmpty(receiverInfoDOS)) {
          ClientReceiverInfoVO receiverInfoVO;
          for (ClientReceiverInfoDO receiverInfoDO : receiverInfoDOS) {
              receiverInfoVO = new ClientReceiverInfoVO();
              BeanUtils.copyProperties(receiverInfoDO, receiverInfoVO);
              receiverInfoVOS.add(receiverInfoVO);
          }
      }
    pageCommonVO.setPageInfo(new PageInfo(receiverInfoDOS));
    pageCommonVO.setPageInfoList(receiverInfoVOS);
    return pageCommonVO;
  }

  /**
   * 当前企业获取在供应商客户信息中维护的自己公司的收货信息(此处自己公司为客户)
   *
   * @param searchParam
   * @param clientOrgId
   * @return
   */
  public List<ClientReceiverInfoVO> listSelfReceiversBySupplier(SupplierDealerSearchParam searchParam, String clientOrgId)
      throws Exception {
    String orgId = getSupplierOrgId(searchParam);
    if (null == orgId) {
      return new ArrayList<>();
    }
    if(StringUtils.isNotBlank(searchParam.getClientOrgId())){
      clientOrgId = searchParam.getClientOrgId();
    }
    CompanyDealerDO dealerDO = companyDealerMapper.itemByOrgId(orgId, clientOrgId);
    if(dealerDO == null){
      return new ArrayList<>();
    }
    ClientReceiverInfoVO clientReceiverInfoVO = new ClientReceiverInfoVO();
    clientReceiverInfoVO.setOrgId(orgId);
    // 相对于上游，自己公司为客户
    clientReceiverInfoVO.setDealerOrgId(dealerDO.getDealerOrgId());
    clientReceiverInfoVO.setReceiverName(searchParam.getReceiverName());
    clientReceiverInfoVO.setPhone(searchParam.getPhone());
    clientReceiverInfoVO.setAddress(searchParam.getAddress());

    List<ClientReceiverInfoVO> receiverInfoVOS = new ArrayList<>();
    List<ClientReceiverInfoDO> receiverInfoDOS = clientReceiverInfoMapper.list(clientReceiverInfoVO);
    if (!CollectionUtils.isEmpty(receiverInfoDOS)) {
      ClientReceiverInfoVO receiverInfoVO ;
      for (ClientReceiverInfoDO receiverInfoDO : receiverInfoDOS) {
        receiverInfoVO = new ClientReceiverInfoVO();
        BeanUtils.copyProperties(receiverInfoDO, receiverInfoVO);
        receiverInfoVOS.add(receiverInfoVO);
      }
    }
    return receiverInfoVOS;
  }

  /**
   * 获取上游公司的orgId。company_supplier表中plat_org_id可能是空的，主机厂的supplier_org_id与plat_org_id一般一致，
   * 所以先判断plat_org_id是否存在，如不存在取supplier_org_id,如果supplier_org_id未查到公司信息，再用sapCode查
   *
   * @param searchParam
   * @return
   */
  private String getSupplierOrgId(SupplierDealerSearchParam searchParam) {
    String orgId = null == searchParam.getSupplierPlatOrgId() ? searchParam.getSupplierOrgId() : searchParam.getSupplierPlatOrgId();
    CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
    if (null == companyInfoDO) {
      companyInfoDO = companyInfoMapper.itemBySap(searchParam.getSupplierCode());
      if (null != companyInfoDO) {
        orgId = companyInfoDO.getOrgId();
      }
    }
    return orgId;
  }

}
